package bookpad.service;

import java.util.List;
import java.util.Map;

import org.slim3.datastore.Datastore;

import bookpad.meta.UserBookMeta;
import bookpad.meta.UserDataMeta;
import bookpad.model.UserBook;
import bookpad.model.UserData;

public class UserDataService extends ServiceBase {

    public UserData getUser(String userId) {
        UserDataMeta t = new UserDataMeta();
        List<UserData> l =
            Datastore.query(t).filter(t.userId.equal(userId)).asList();
        return isEmpty(l) ? null : l.get(0);
    }

    public List<UserBook> getBooks(String userId, String status) {
        UserBookMeta t = new UserBookMeta();
        AmazonService as = new AmazonService();
        List<UserBook> l =
            Datastore
                .query(t)
                .filter(t.userId.equal(userId), t.status.equal(status))
                .asList();
        for (UserBook ub : l) {
            Map<String, String> item = as.getItem(ub.getASIN());
            ub.setItem(item);
        }
        return l;
    }

    public UserBook getBook(String userId, String ASIN) {
        UserBookMeta t = new UserBookMeta();
        List<UserBook> l =
            Datastore
                .query(t)
                .filter(t.userId.equal(userId), t.ASIN.equal(ASIN))
                .asList();
        return isEmpty(l) ? null : l.get(0);
    }
}
